package com.cqhz.quwan.ui.main.pager;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckedTextView;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.cqhz.quwan.APP;
import com.cqhz.quwan.R;
import com.cqhz.quwan.common.KeyContract;
import com.cqhz.quwan.model.BetOrder;
import com.cqhz.quwan.model.FocusBean;
import com.cqhz.quwan.model.LoginBean;
import com.cqhz.quwan.model.OrderResp;
import com.cqhz.quwan.service.OrderService;
import com.cqhz.quwan.ui.activity.FootballLotteryActivity;
import com.cqhz.quwan.ui.activity.GoPaymentActivity;
import com.cqhz.quwan.ui.buy.event.EventObj;
import com.cqhz.quwan.ui.login.LoginActivity;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import me.militch.quickcore.mvp.model.ModelHelper;
import me.militch.quickcore.util.ApiException;
import me.militch.quickcore.util.EventCall;

/**
 * @author whamu2
 * @date 2018/6/11
 */
public class CardPagerAdapter extends PagerAdapter implements CardAdapter {

    private Context mContext;
    private List<View> mViews;
    private List<CardItem> mData;
    private Context context;
    private ModelHelper modelHelper;
    private BindAlipayClickListener listener;

    public CardPagerAdapter(Context context, ModelHelper modelHelper) {
        mData = new ArrayList<>();
        mViews = new ArrayList<>();
        this.context = context;
        this.modelHelper = modelHelper;
    }

    public void setBindAlipayClickListener(BindAlipayClickListener listener) {
        this.listener = listener;
    }

    public void addCardItem(Context context, CardItem item) {
        mContext = context;
        mViews.add(null);
        mData.add(item);
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        View view = LayoutInflater.from(container.getContext())
                .inflate(R.layout.item_pager_focus, container, false);
        container.addView(view);
        bind(mData.get(position), view);
        View cardView = view.findViewById(R.id.cardView);

        mViews.set(position, cardView);
        return view;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((View) object);
        mViews.set(position, null);
    }

    private void bind(CardItem item, View view) {
        ViewHolder holder = null;
        if (holder == null) {
            holder = new ViewHolder(view);
        }
        holder.bind(item);
    }


    public class ViewHolder implements View.OnClickListener {
        ImageView mHostTeamImageView;
        ImageView mGuestTeamImageView;
        TextView mGameNameTextView;
        TextView mGameDesTextView;
        TextView mTVMatchScore;

        CheckedTextView mHostVictoryCheckedTextView;
        CheckedTextView mTieCheckedTextView;
        CheckedTextView mGuestVictoryCheckedTextView;

        RadioGroup mAmountRadioGroup;
        private FocusBean data;

        public ViewHolder(View itemView) {
            mHostTeamImageView = itemView.findViewById(R.id.iv_host_team);
            mGuestTeamImageView = itemView.findViewById(R.id.iv_guest_team);
            mGameNameTextView = itemView.findViewById(R.id.tv_game_name);
            mGameDesTextView = itemView.findViewById(R.id.tv_game_des);
            mTVMatchScore = itemView.findViewById(R.id.tv_match_score);

            mHostVictoryCheckedTextView = itemView.findViewById(R.id.ctv_host_victory);
            mHostVictoryCheckedTextView.setOnClickListener(this);
            mTieCheckedTextView = itemView.findViewById(R.id.ctv_tie);
            mTieCheckedTextView.setOnClickListener(this);
            mGuestVictoryCheckedTextView = itemView.findViewById(R.id.ctv_guest_victory);
            mGuestVictoryCheckedTextView.setOnClickListener(this);

            mAmountRadioGroup = itemView.findViewById(R.id.rg_amount);
            mAmountRadioGroup.check(R.id.rb_amount_10);
            itemView.findViewById(R.id.action_apply).setOnClickListener(this);
            itemView.findViewById(R.id.action_goto_more).setOnClickListener(this);
        }

        void bind(CardItem item) {
            data = item.getData();
            if (data != null) {
                Glide.with(mContext).load(data.getHostTeamLogo()).apply(new RequestOptions().error(R.mipmap.icon_default_img)).into(mHostTeamImageView);
                Glide.with(mContext).load(data.getGuestTeamLogo()).apply(new RequestOptions().error(R.mipmap.icon_default_img)).into(mGuestTeamImageView);
                mGameNameTextView.setText(data.getLeague());
                mGameDesTextView.setText(MessageFormat.format("{0}{1}截止", data.getWeek(), data.getCloseTime()));

                mHostVictoryCheckedTextView.setText(MessageFormat.format("{0} 胜\n{1}",
                        data.getHostTeam(), data.getPassStatus() != 0 ? data.getOddsMap().get_$0() : data.getOddsMap().get_$3()));

                mTieCheckedTextView.setText(MessageFormat.format("平\n{0}",
                        data.getPassStatus() != 0 ? data.getOddsMap().get_$1() : data.getOddsMap().get_$4()));

                mGuestVictoryCheckedTextView.setText(MessageFormat.format("{0} 胜\n{1}",
                        data.getGuestTeam(), data.getPassStatus() != 0 ? data.getOddsMap().get_$2() : data.getOddsMap().get_$5()));

                switch (data.getPassStatus()) {
                    case 0:
                        mTVMatchScore.setText(data.getScore());
                        mTVMatchScore.setTextColor(Color.parseColor(Integer.parseInt(data.getScore()) > 0 ? "#FF1C19" : "#04B431"));
                        break;
                    case 1:
                        mTVMatchScore.setText("");
                        break;
                    default:
                }
            }
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.action_apply:
                    LoginBean loginBean = APP.Companion.get().getLoginInfo();
                    if (loginBean == null || loginBean.getUserId() == null) {
                        Intent intent = new Intent(context, LoginActivity.class);
                        context.startActivity(intent);
                        return;
                    }
                    int amount = getAmount();
                    Set<Integer> selected = getSelected();
                    if (selected.size() <= 0) {
                        Toast.makeText(context, "请选择投注", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    int payAmount = selected.size() * amount * 2 * 100;
                    String orderBetJson = resoverSelected(data.getCode(), selected);
                    Map<String, String> params = new HashMap<>();
                    params.put("userId", loginBean.getUserId());
                    params.put("lotteryId", data.getLotteryId().toString());
                    params.put("period", data.getCode());
                    params.put("buyWay", "0");
                    params.put("payAmount", String.valueOf(payAmount));
                    params.put("betNum", String.valueOf(selected.size()));
                    params.put("betTimes", String.valueOf(amount));
                    params.put("betBunch", "1-1");
                    params.put("betAppend", "");
                    params.put("append", "");
                    params.put("realName", "");
                    params.put("mobile", "");
                    params.put("idCard", "");
                    params.put("orderBetJson", orderBetJson);
                    EventBus.getDefault().post(new EventObj(0x9999, true));
                    modelHelper.request(modelHelper.getService(OrderService.class).postOrder(params), new EventCall<OrderResp>() {
                        @Override
                        public void call(OrderResp orderResp) {
                            EventBus.getDefault().post(new EventObj(0x9999, false));
                            Intent intent = new Intent(context, GoPaymentActivity.class);
                            intent.putExtra(KeyContract.Amount, Double.valueOf(orderResp.getPayAmount()));
                            intent.putExtra(KeyContract.ActualAmount, Double.valueOf(orderResp.getPayAmount()));
                            String lotteryName = "竞猜足球-单关固定";
                            intent.putExtra(KeyContract.LotteryName, lotteryName);
                            intent.putExtra(KeyContract.OrderId, orderResp.getId());
                            context.startActivity(intent);
                        }
                    }, new EventCall<ApiException>() {
                        @Override
                        public void call(ApiException e) {
                            EventBus.getDefault().post(new EventObj(0x9999, false));
                            if (e.getCode() == 10008) {
                                listener.onBindAlipayClick();
                            } else {
                                Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                    break;
                case R.id.action_goto_more:
                    Intent intent = new Intent(context, FootballLotteryActivity.class);
                    intent.putExtra(KeyContract.LotteryId, data.getLotteryId());
                    intent.putExtra(KeyContract.Position, 0);
                    context.startActivity(intent);
                    break;
                case R.id.ctv_host_victory:
                    mHostVictoryCheckedTextView.toggle();
                    break;
                case R.id.ctv_tie:
                    mTieCheckedTextView.toggle();
                    break;
                case R.id.ctv_guest_victory:
                    mGuestVictoryCheckedTextView.toggle();
                    break;
            }
        }

        private Set<Integer> getSelected() {
            Set<Integer> selected = new LinkedHashSet<>();
            if (mHostVictoryCheckedTextView.isChecked()) {
                selected.add(data.getPassStatus() != 0 ? 0 : 3);
            }
            if (mTieCheckedTextView.isChecked()) {
                selected.add(data.getPassStatus() != 0 ? 1 : 4);
            }
            if (mGuestVictoryCheckedTextView.isChecked()) {
                selected.add(data.getPassStatus() != 0 ? 2 : 5);
            }
            return selected;
        }


        private String resoverSelected(String p, Set<Integer> selected) {
            List<BetOrder> betOrders = new ArrayList<>();
            String ss = selected.toString().replace("[", "")
                    .replace("]", "").replace(", ", ",");
            betOrders.add(new BetOrder(p, ss, 7));
            Gson gson = new Gson();
            return gson.toJson(betOrders);
        }

        /**
         * 获取倍数
         *
         * @return Amount
         */
        private int getAmount() {
            int AMOUNT;
            switch (mAmountRadioGroup.getCheckedRadioButtonId()) {
                case R.id.rb_amount_10:
                    AMOUNT = Amount.AMOUNT_10;
                    break;
                case R.id.rb_amount_20:
                    AMOUNT = Amount.AMOUNT_20;
                    break;
                case R.id.rb_amount_50:
                    AMOUNT = Amount.AMOUNT_50;
                    break;
                default:
                    AMOUNT = Amount.AMOUNT_10;
                    break;
            }
            return AMOUNT;
        }
    }

    private interface Amount {
        int AMOUNT_10 = 10;
        int AMOUNT_20 = 50;
        int AMOUNT_50 = 99;
    }

    public interface BindAlipayClickListener {
        /**
         * 点击绑定支付宝
         */
        void onBindAlipayClick();
    }
}
